package com.cgmnx.admin.web.controller;

import com.cgmnx.admin.biz.RankNumBiz;
import com.cgmnx.admin.common.bean.ApiRes;
import com.cgmnx.admin.common.util.WebUtils;
import com.cgmnx.admin.dao.condition.RankNumCondition;
import com.cgmnx.admin.dao.entity.RankNumAndNoteEntity;
import com.cgmnx.admin.dao.entity.RankNumEntity;
import com.cgmnx.admin.model.enums.RankNumType;
import com.cgmnx.admin.web.converter.entity.RankNumConditionConverter;
import com.cgmnx.admin.web.converter.entity.RankNumEntityConverter;
import com.cgmnx.admin.web.converter.vm.RankNumVmConverter;
import com.cgmnx.admin.web.model.param.RankNumQueryParam;
import com.cgmnx.admin.web.model.vm.RankNumAndNoteVm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * @Author: zongjiantao
 * @Description: $Description$
 * @Date: Created in 18:42 2018/8/11
 * @Modified By:
 */
@Slf4j
@RestController
@RequestMapping("/cgmnx/rankNum")
public class RankNumController {
    @Autowired
    private RankNumBiz rankNumBiz;

    @Autowired
    private RankNumVmConverter converter;

    @Autowired
    private RankNumConditionConverter conditionConverter;

    @RequestMapping("/queryPage.json")
    public ApiRes queryPage(@RequestBody @Valid RankNumQueryParam param, BindingResult result) {

        if (result.hasErrors()) {
            return ApiRes.returnFail(WebUtils.resolveBindingResult(result));
        }
        final RankNumCondition condition = conditionConverter.convert(param);
        final int count = rankNumBiz.count(condition);

        if (count < 1) {
            return ApiRes.emptyList();
        }

        List<RankNumAndNoteEntity> entityList = rankNumBiz.queryPage(condition);

        if (CollectionUtils.isEmpty(entityList)) {
            return ApiRes.emptyList();
        }

        final List<RankNumAndNoteVm> rankNumAndNoteVm = converter.convert(entityList);

        return ApiRes.list(rankNumAndNoteVm, count);
    }

    @RequestMapping("/update.json")
    @ResponseBody
    public ApiRes<RankNumEntity> update(Integer id, int rankType) {

        final RankNumEntity rankNumEntity = rankNumBiz.getQueryById(id);
        if (rankType == 1) {
            rankNumEntity.setRankNum(rankNumEntity.getRankNum() + 1);
        }
        rankNumEntity.setRankType(RankNumType.codeOf(rankType));
        rankNumBiz.update(rankNumEntity);

        return ApiRes.returnSuccess();
    }

}
